package start;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class Aufgabe2 {
	
	private String dbURL = "jdbc:oracle:thin:@oracle-srv.edvsz.hs-osnabrueck.de:1521:ora11";
	private Scanner ein = new Scanner(System.in);
	private String login;
	private String password;
	Connection conn;
	
	public Aufgabe2() {
		//loading jdbc driver
				try {
					Class.forName("oracle.jdbc.driver.OracleDriver");
				} catch (ClassNotFoundException e) {
					System.err.println("Could not load JDBC driver.");
					e.printStackTrace();
				}
				
				//request for username and password
				System.out.print("Benutzername: ");
				login = ein.nextLine();
				
				System.out.print("Passwort: ");
				password = ein.nextLine();
				
				
				//connection to db
				try {
					conn = DriverManager.getConnection(dbURL, login, password);
				} catch (SQLException e) {
					System.err.println("ErrorCode: " + e.getErrorCode());
					System.err.print(e.getMessage());
				}
				
				System.out.println("Connected successfully.");
				aufgabe2bb();
				
	}
	
	public void aufgabe2bb() {
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			conn.setAutoCommit(false); //Auto Commit ausstellen
		} catch (SQLException e1) {
			System.err.println("Could not create statement");
			e1.printStackTrace();
		}
		
		//Usereingaben
		String k1ID;
		String k1Name;
		String k2ID;
		String k2Name;
		
		System.out.print("Kunde 1 ID: ");
		k1ID = ein.nextLine();
		
		System.out.print("Kunde 1 Name: ");
		k1Name = ein.nextLine();
		
		System.out.print("Kunde 2 ID: ");
		k2ID = ein.nextLine();
		
		System.out.print("Kunde 2 Name: ");
		k2Name = ein.nextLine();
		
		//Executen
		String exeString1 = "INSERT INTO kunde VALUES(" + k1ID + ", '" + k1Name + "')";
		String exeString2 = "INSERT INTO kunde VALUES(" + k2ID + ", '" + k2Name + "')";
		
		
		try {
			stmt.executeQuery(exeString1);
			stmt.executeQuery(exeString2);
			conn.commit();
			conn.setAutoCommit(true); //Auto Commit zurücksetzen
		} catch (SQLException e) {
			System.err.println("Konnte Kommando nicht ausführen. Rollback.");
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				System.err.println("Konnte Rollback nicht ausführen!");
				e1.printStackTrace();
			}
		}
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Aufgabe2();
	}

}
